<template>
  <div class="main">
    <div class="main-left">
      <div id="container" style="width: 100%; height: 100%;"></div>
      <div class="mapSearchBox">
        <div class="">
          <a-row :gutter="[0, 0]">
            <a-col :span="24">
              <a-input-search
                placeholder="搜索地图"
                enter-button
                @click="placeSearchClear"
                @search="searchAddress"
              />
            </a-col>
          </a-row>
        </div>

        <!-- <div class="">
          <span>地图搜索</span>
          <input v-model="seachMapValue" id="mapSearchInput" />
          <button @click="searchAddress">搜索</button>
        </div> -->
        <div id="panel"></div>
      </div>
    </div>
    <div class="main-right">
      <div class="main-row">
        <div class="title">
          <span>打卡记录</span>
        </div>
      </div>
      <div class="main-row">
        <div class="checkedBox">
          <div class="item">
            <div class="top">
              <span>{{ checkInfo.day }}</span>
            </div>
            <div class="botton"><span>今日签到(人/次)</span></div>
          </div>
          <div class="item">
            <div class="top">
              <span>{{ checkInfo.month }}</span>
            </div>
            <div class="botton"><span>本月签到</span></div>
          </div>
        </div>
      </div>
      <div class="main-row" style="margin-bottom: 4px;">
        <a-row :gutter="[8, 8]">
          <a-col :span="24"
            ><a-input placeholder="搜索地点/人员" v-model="keyword" allow-clear>
              <a-icon slot="prefix" type="search" /> </a-input
          ></a-col>
          <!-- <a-col :span="0">
          </a-col> -->
        </a-row>
        <a-row :gutter="[8, 8]">
          <a-col :span="20"
            ><a-range-picker
              :placeholder="['开始时间', '结束时间']"
              :value="rangeTime"
              @change="onRangePickerChange"
          /></a-col>
          <a-col :span="4">
            <a-button
              type="primary"
              class="searchButton"
              @click="searchMarkerlists"
              >确定</a-button
            >
          </a-col>
        </a-row>
      </div>
      <div class="main-list">
        <div class="wrap">
          <div
            class="item"
            v-for="(item, index) in positionLists"
            :key="index"
            @click="pointHandle(item)"
          >
            <div>
              <div class="">
                <div class="name">
                  <div>
                    <span>{{ item.employeeName }}</span>
                  </div>
                  <div>
                    <span>{{ item.time }}</span>
                  </div>
                </div>
                <div class="address">
                  <div><span>签到地址</span></div>
                  <div>
                    <span>{{ item.city }} {{ item.address }}</span>
                  </div>
                </div>
                <div class="remark">
                  <div><span>签到注备</span></div>
                  <div>
                    <span>{{ item.remarks }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="main-row" v-if="isShowPagination">
        <div class="pagination">
          <a-pagination
            size="small"
            v-model="pagination.current"
            :pageSize="pagination.pageSize"
            :total="pagination.total"
            :show-total="total => `${total} 条`"
            @change="onChangePagination"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from "@/server/userConfig";
import { initUserInfo } from "@/unit/tool";
import AMapLoader from "@amap/amap-jsapi-loader";

function getAddress(str) {
  // return str
  //   .split(":")
  //   .slice(0, 1)
  //   .toString();
  return str;
}

function getPosition(str) {
  return str.split(",");
}

function getTime(str) {
  // 获取时分秒
  let time = str
    .split(" ")
    .slice(-1)
    .toString();
  return time
    .split(":")
    .slice(0, 2)
    .join(":");
}

function buildCheckOutRecord(lists) {
  let Geocoder = new AMap.Geocoder();
  let maxSize = 20;
  let length = lists.length;
  let groupCount = Math.ceil(length / maxSize);
  let positionLists = [];
  let positionDetailLists = [];
  let newLists = [];

  for (let i = 0; i < groupCount; i++) {
    positionLists.push([]);
  }

  for (let j = 0; j < lists.length; j++) {
    if (j == 46) {
      debugger;
    }
    let index = Math.floor(j / maxSize);
    positionLists[index].push(getPosition(lists[j].addressGps));
  }

  return new Promise(async (resolve, reject) => {
    for (let k = 0; k < positionLists.length; k++) {
      let locationLists = positionLists[k];
      let addressLists = await getAddress(locationLists);
      positionDetailLists.push(addressLists);
    }

    let _positionDetailLists = [].concat(...positionDetailLists);

    let _lists = lists.map((item, index) => {
      if (index == 47) {
        debugger;
      }
      return {
        ...item,
        address: _positionDetailLists[index].formattedAddress,
        city: _positionDetailLists[index].addressComponent.city,
        province: _positionDetailLists[index].addressComponent.province
      };
    });
    resolve(_lists);
  });

  function getAddress(locationLists) {
    return new Promise((resolve, reject) => {
      Geocoder.getAddress(locationLists, (status, result) => {
        if (status === "complete" && result.info === "OK") {
          resolve(result.regeocodes);
        } else {
          console.log("根据经纬度查询地址失败");
        }
      });
    });
  }
}

export default {
  name: "signMap",
  components: {},
  data() {
    return {
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      userName: "",
      role: "",
      compId: "",
      district: "所有片区",
      keyword: "",
      isShowPagination: false,
      rangeTime: [],
      checkInfo: "",
      map: "",
      positionLists: [],
      seachMapValue: "",
      placeSearch: "",
      autoComplete: ""
    };
  },
  methods: {
    async initAMapLoader() {
      return new Promise(async (resolve, reject) => {
        try {
          let AMap = await AMapLoader.load({
            key: "6a857e379436047b2e3ebb377f1aaa60", // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: [
              "AMap.Scale",
              "AMap.ToolBar",
              "AMap.PlaceSearch",
              "AMap.Autocomplete",
              "AMap.Geocoder"
            ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            AMapUI: {
              // 是否加载 AMapUI，缺省不加载
              version: "1.1", // AMapUI 缺省 1.1
              plugins: [] // 需要加载的 AMapUI ui插件
            },
            Loca: {
              // 是否加载 Loca， 缺省不加载
              version: "1.3.2" // Loca 版本，缺省 1.3.2
            }
          });
          this.map = new AMap.Map("container", {
            resizeEnable: true,
            center: [114.39854, 30.4483],
            zoom: 13
          });

          // 设置Autocomplete配置
          const autoOptions = {
            // 城市，默认全国
            city: "全国",
            // 使用联想输入的input的id
            input: "mapSearchInput"
          };

          // 设置searchOptions配置
          const searchOptions = {
            map: this.map,
            panel: "panel",
            city: "全国", //城市
            type: "", //数据类别
            pageSize: 5, //每页结果数,默认10
            pageIndex: 1, //请求页码，默认1
            extensions: "base" //返回信息详略，默认为base（基本信息）
          };

          // 加载插件
          // this.map.addControl(new AMap.Scale());
          // this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.PlaceSearch());
          // this.map.addControl(new AMap.Autocomplete());

          // 地图搜索自动填充加载
          // this.autoComplete = new AMap.Autocomplete(autoOptions);
          // 地图搜索插件加载 , 构造地点查询类
          this.placeSearch = new AMap.PlaceSearch(searchOptions);

          //注册监听，当选中某条记录时会触发
          // autoComplete.on("select", e => {
          //   debugger;
          //   placeSearch.setCity(e.poi.adcode);
          //   placeSearch.search(e.poi.name); //关键字查询查询
          // });

          resolve();
        } catch (error) {
          console.log(error);
        }
      });
    },

    placeSearchClear() {
      this.placeSearch.clear();
    },

    searchAddress(value) {
      this.placeSearch.search(value, (status, result) => {
        console.log(status, result);
      });

      this.keyword = "";
      this.rangeTime = [];
      this.getMarkerLists({ keyword: "default", current: -1 });
    },

    // selectAddress(e) {
    //   //这里获得点选地点的经纬度
    //   let location = e.selected.data.location;
    //   console.log("lng", location.lng);
    //   console.log("lat", location.lat);
    //   // Do Something
    // },

    searchMarkerlists() {
      this.getMarkerLists({ current: 1 });
    },

    getMarkerLists(searchObj) {
      this.isShowPagination =
        searchObj && searchObj.keyword == "default" ? false : true;
      return new Promise(async (resolve, reject) => {
        try {
          const res = await api.getMarkerLists({
            username: this.userName,
            role: this.role,
            compId: this.compId,
            district: "所有片区",
            startTime: this.rangeTime[0] ? `${this.rangeTime[0]} 00:00:00` : "",
            endTime: this.rangeTime[1] ? `${this.rangeTime[1]} 23:59:59` : "",
            keyword:
              searchObj && searchObj.keyword ? searchObj.keyword : this.keyword,
            pageNum:
              searchObj && searchObj.current
                ? searchObj.current
                : this.pagination.current,
            pageSize: this.pagination.pageSize
          });
          if (res.MsgCode !== 0) {
            return;
          }

          this.map.clearMap();

          this.pagination.total = res.Data.total;
          let lists = await buildCheckOutRecord(
            validateGpsLists(res.Data.rows)
          );

          function validateGpsLists(lists) {
            let _lists = [];

            _lists = lists.filter((item, index) => {
              let { addressGps } = item;
              let ary = addressGps.split(",");

              return ary !=',' && Array.isArray(ary) && ary.length == 2;
            });

            return _lists;
          }

          this.positionLists = lists.map(item => {
            let marker = {
              address: getAddress(item.address),
              position: getPosition(item.addressGps),
              city: item.city,
              id: item.id,
              employeeName: item.name,
              province: item.province,
              remarks: item.remarks || "无备注",
              time: item.time
            };

            this.createMarker(marker);

            return marker;
          });

          this.map.setFitView();

          resolve();
        } catch (error) {
          console.log(error);
        }
      });
    },

    createMarker(item) {
      let circleMarker = new AMap.CircleMarker({
        map: this.map,
        center: item.position,
        radius: 12,
        strokeColor: "white",
        strokeWeight: 2,
        strokeOpacity: 0.5,
        fillColor: "rgba(255,0,0,1)",
        fillOpacity: 0.7,
        zIndex: 10,
        bubble: true,
        cursor: "pointer",
        clickable: true
      });

      circleMarker.on("click", e => {
        this.map.setCenter(e.target.getCenter());
        // this.map.setZoom(20);
        let infoWindow = this.createInfoWindow(item);
        infoWindow.open(this.map, e.target.getCenter());
      });
    },

    createInfoWindow(item) {
      return new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        //传入 dom 对象，或者 html 字符串
        content: `<div id='mapInfoBox' class='mapInfoBox'>
                    <div><span class='address'>${item.city} ${item.address}</span></div>
                    <div><span class='name'>${item.employeeName}</span><span class='time'>${item.time}</span></div>
                    <div><span class='remark'>${item.remarks}</span></div>
                  </div>`,
        offset: new AMap.Pixel(0, -12)
      });
    },

    async getChecked() {
      const res = await api.getCheckTimeCounts({
        username: this.userName
      });
      // this.isLoading = false;
      console.log(res);

      if (res.MsgCode !== 0) {
        return;
      }

      this.checkInfo = res.Data;
    },

    pointHandle(item) {
      // const marker = new AMap.Marker({
      //   position: [116.406315, 39.908775] //位置
      // });
      console.log(item);
      this.map.setCenter(item.position);
      // this.map.setZoom(20);
      let infoWindow = this.createInfoWindow(item);
      infoWindow.open(this.map, item.position);
    },

    onRangePickerChange(date, dateString) {
      this.rangeTime = dateString;
      console.log(this.rangeTime);
    },

    onChangePagination(value) {
      this.getMarkerLists({ current: Number(value) });
    },

    async initPage() {
      await initUserInfo(this);
      this.getChecked();
      await this.initAMapLoader();
      await this.getMarkerLists({ keyword: "default", current: -1 });
    }
  },
  created() {
    this.initPage();
  }
};
</script>

<style>
#mapInfoBox.mapInfoBox {
  padding: 10px 12px;
  background: #000000;
  opacity: 0.7;
  border-radius: 6px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #ffffff;
  line-height: 24px;
}

#mapInfoBox.mapInfoBox .address {
  font-size: 12px;
}

#mapInfoBox.mapInfoBox .name {
  margin-right: 24px;
  font-size: 18px;
  line-height: 36px;
}

#mapInfoBox.mapInfoBox .time {
  line-height: 36px;
}

#mapInfoBox.mapInfoBox .remark {
  font-size: 12px;
}
</style>

<style scoped="scoped">
.mapSearchBox {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 16px;
  left: 16px;
  width: 320px;
}

#panel {
  /* position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 16px;
  left: 16px;
  width: 280px; */
}

.main {
  display: flex;
  width: 100%;
  height: 100%;
  background-color: #ecf2f7;
  flex: 1;
  padding: 12px 12px 12px 12px;
}

.main-left {
  flex: 1;
  height: 100%;
  position: relative;
  margin-right: 12px;
}

.main-right {
  width: 400px;
  height: 100%;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  padding: 0px 12px;
}

.main-row {
  width: 100%;
  /* height: 100px; */
  /* background-color: indianred; */
}

.main-row > .title {
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: 600;
  color: #1890ff;
  padding-top: 25px;
  padding-left: 16px;
  margin-bottom: 16px;
}

.main-row > .checkedBox {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: stretch;
  margin-bottom: 12px;
}

.main-row > .checkedBox > .item {
  flex: 1;
}

.checkedBox > .item > .top {
  text-align: center;
  font-size: 40px;
  font-family: Microsoft YaHei;
  font-weight: 600;
  color: #1890ff;
  line-height: 58px;
}

.checkedBox > .item > .botton {
  text-align: center;
  font-size: 12px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #4b4b4b;
  line-height: 18px;
}

.main-row .searchButton.ant-btn.ant-btn-primary {
  padding-left: 0px;
  padding-right: 0px;
  width: 100%;
}

.main-list {
  width: 100%;
  flex: 1;
  background-color: #ffffff;
  overflow-y: auto;
  border: 1px solid #e5e5e5;
}

.main-list > .wrap {
}

.main-list > .wrap > .item {
  background-color: #ffffff;
  width: 100%;
  padding: 2px 12px 2px 12px;
  border-bottom: 1px solid #e5e5e5;
  cursor: pointer;
}

.main-list > .wrap > .item .name,
.main-list > .wrap > .item .address,
.main-list > .wrap > .item .remark {
  display: flex;
}

.main-list > .wrap > .item .name > div:first-child {
  width: 80px;
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #1890ff;
  line-height: 35px;
}

.main-list > .wrap > .item .name > div:last-child {
  flex: 1;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #1890ff;
  line-height: 35px;
}

.main-list > .wrap > .item .address > div:first-child,
.main-list > .wrap > .item .remark > div:first-child {
  width: 72px;
  font-size: 12px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #161616;
  line-height: 24px;
}

.main-list > .wrap > .item .address > div:last-child,
.main-list > .wrap > .item .remark > div:last-child {
  flex: 1;
  /* height: 20px; */
  font-size: 12px;
  font-family: Microsoft YaHei;
  font-weight: 100;
  color: #161616;
  line-height: 24px;
}

.main-row > .pagination {
  height: 40px;
  padding-top: 8px;
  text-align: right;
}
</style>
